const speakeasy = require('speakeasy');
const db = require('./db');
const logger = (message) => {
    const now = new Date();
    const chinaTime = new Date(now.getTime() + 8 * 60 * 60 * 1000);
    const chinaTimeStr = chinaTime.toISOString().replace('Z', '+08:00');
    console.log(`[${chinaTimeStr}] ${message}`);
};
// 生成TOTP密钥和当前令牌
function generateOTP(secret) {
    // 生成一个随机密钥
    const secret_new = speakeasy.generateSecret({
        name: 'qxglgj'
    });

    let secret_ = '';

    if (secret === null) {
        secret_ = secret_new.base32;
    } else {
        secret_ = secret;
    }

    // 获取当前时间的TOTP令牌
    const token = speakeasy.totp({
        secret: secret_,
        encoding: 'base32',
        window: 0 // 只使用当前时间窗口
    });

    return {
        secret: secret_, // 返回base32格式的密钥
        token // 返回当前令牌
    };
}

// 验证TOTP令牌
function verifyOTP(secret, token) {
    logger(`验证TOTP令牌:${secret},${token}`);
    return speakeasy.totp.verify({
        secret: secret,
        encoding: 'base32',
        token: token,
        window: 1 // 允许±1个时间窗口的误差
    });
}

// 生成TOTP URL，用于手动添加到认证App
function generateTotpUrl(secret, accountName) {
    return speakeasy.otpauthURL({
        secret: secret,
        label: accountName,
        issuer: 'qxglgj',
        encoding: 'base32'
    });
}

module.exports = { generateOTP, verifyOTP, generateTotpUrl };